<!-- src/modules/dashboard/components/DataChart.vue -->
<template>
  <div class="chart-container" ref="chartRef" style="width: 100%; height: 400px;"></div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';

export default defineComponent({
  name: 'DataChart',
  props: {
    chartData: {
      type: Array,
      required: true
    },
    chartTitle: {
      type: String,
      default: '图表标题'
    }
  },
  setup(props) {
    const chartRef = ref<HTMLDivElement | null>(null);
    let chartInstance: echarts.ECharts | null = null;

    onMounted(() => {
      if (chartRef.value) {
        chartInstance = echarts.init(chartRef.value);
        updateChart(props.chartData);
      }
    });

    onBeforeUnmount(() => {
      chartInstance?.dispose();
    });

    const updateChart = (data: any) => {
      const option = {
        title: {
          text: props.chartTitle,
        },
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          data: data.map((item: any) => item.name),
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            data: data.map((item: any) => item.value),
            type: 'line',
          },
        ],
      };
      chartInstance?.setOption(option);
    };

    return { chartRef };
  },
});
</script>

<style scoped>
.chart-container {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
}
</style>
